/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gui;

import interfaces.EditPanel;

import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import database.DBConnectionFactory;

/**
 * Settings panel for personalities
 * 
 * 
 */
public class WorkersPanel extends JPanel implements EditPanel {
   private static final long serialVersionUID = 4228896307757033356L;
   private JTextField nick;
   private JTextField password;
   private JCheckBox active;
   private JTextField priority;
   private String itemName;
   private final DialogPanel parent;

   public WorkersPanel(final DialogPanel parent) {
	  super();
	  this.parent = parent;
	  initialize();
   }

   @Override
   public final void checkInputs() {
	  if (nick.getText().equals("")) {
		 parent.setSaveButtonEnabled(false);
	  } else if (password.getText().equals("")) {
		 parent.setSaveButtonEnabled(false);
	  } else if (!priority.getText().matches("[0-9]{1,2}")) {
		 parent.setSaveButtonEnabled(false);
	  } else {
		 parent.setSaveButtonEnabled(true);
	  }
   }

   @Override
   public boolean delete() {
	  if (nick.getText().equals(""))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM worker WHERE nick = ?");
		 ps.setString(1, itemName);
		 ps.executeUpdate();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }

   @Override
   public String getItemName() {
	  return itemName;
   }

   /**
    * Initializes the components
    */
   private void initialize() {
	  setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
	  nick = new JTextField();
	  nick.setPreferredSize(new Dimension(300, 20));
	  nick.getDocument().addDocumentListener(new MyDocumentListener(this));
	  password = new JTextField();
	  password.setPreferredSize(new Dimension(300, 20));
	  password.getDocument().addDocumentListener(new MyDocumentListener(this));
	  priority = new JTextField();
	  priority.setPreferredSize(new Dimension(300, 20));
	  priority.getDocument().addDocumentListener(new MyDocumentListener(this));
	  active = new JCheckBox();
	  active.setPreferredSize(new Dimension(300, 20));
	  active.setText("Select to run");
	  active.addChangeListener(new javax.swing.event.ChangeListener() {
		 @Override
		 public void stateChanged(final javax.swing.event.ChangeEvent e) {
			checkInputs();
		 }
	  });

	  this.add(new CustomPanel(new CustomLabel("Nick", 80, 20), nick));
	  this.add(new CustomPanel(new CustomLabel("Password", 80, 20), password));
	  this.add(new CustomPanel(new CustomLabel("Priority", 80, 20), priority));
	  this.add(new CustomPanel(new CustomLabel("Active", 80, 20), active));
   }

   @Override
   public JPanel load(final String item) {
	  itemName = item;
	  removeAll();
	  validate();
	  initialize();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM worker WHERE nick = ?");
		 ps.setString(1, item);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			nick.setText(rs.getString("nick"));
			password.setText(rs.getString("password"));
			priority.setText(String.valueOf(rs.getInt("priority")));
			active.setSelected(rs.getBoolean("active"));
		 } else {
			nick.setText(item);
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return this;
   }

   @Override
   public boolean save() {
	  if (nick.getText().equals("") || password.getText().equals("") || !priority.getText().matches("[0-9]{1,2}"))
		 return false;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM worker WHERE nick = ?");
		 ps.setString(1, itemName);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE worker SET " + "nick = ?,password = ?,priority = ?,active = ? WHERE nick = ?");
			ps.setString(1, nick.getText());
			ps.setString(2, password.getText());
			ps.setInt(3, Integer.parseInt(priority.getText()));
			ps.setBoolean(4, active.isSelected());
			ps.setString(5, itemName);
			ps.executeUpdate();
		 } else {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("INSERT INTO worker VALUES(?,?,?,?)");
			ps.setString(1, nick.getText());
			ps.setString(2, password.getText());
			ps.setBoolean(3, active.isSelected());
			ps.setInt(4, Integer.parseInt(priority.getText()));
			ps.executeUpdate();
		 }
		 itemName = nick.getText();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }
}
